/*
 * @Author: venusJin
 * @Date: 2018-04-02 18:32:10
 * @Last Modified by: jinxing@birdpush.com
 * @Last Modified time: 2018-04-02 19:04:06
 */
import Vue from 'vue'
import Router from 'vue-router'
import Auth from './views/auth.vue'
import Game from './views/game.vue'
import { DealErrHref, GetQueries } from './util.js'
import store from './store.js'

Vue.use(Router)

// 'http://temporary.birdjia.com/index.html?from=singlemessage&code=222#/?showId=22'
let resultUrl = DealErrHref()
if (resultUrl) {
  window.location.href = resultUrl
}
let beforeAuthUrl = window.location.href
let code = GetQueries().code ? GetQueries().code : null
const routes = [
  {
    path: '/auth',
    name: 'auth',
    component: Auth
  },
  {
    path: '/',
    name: 'game',
    component: Game
  }
]

const router = new Router({
  routes
})

// 未登录 => 缓存url参数，跳转auth => 跳转wx，wx返回code => 取出code，获取登录，缓存登录 => 获取缓存url参数，并删除缓存，跳回去
store.commit('initUser')
router.beforeEach((to, from, next) => {
  console.log(to, store)
  // 验证是否登录
  if (!store.state.user && to.path !== '/auth') {
    // 授权处理页面，把所有参数信息都带过去
    if (code) {
      // 步骤 2
      next({
        path: '/auth',
        query: {
          code
        }
      })
    } else {
      // 步骤 1
      localStorage.setItem('beforeAuthUrl', beforeAuthUrl)
      next('/auth')
    }
  }
  next()
})

export default router
